package application

import (
	"awesomeProject/config"
	"awesomeProject/handle"
	"awesomeProject/models"
	"fmt"
	"time"
)

func RunFunc() {
	coefficient := config.LoadCoefficient()

	db, err := models.ConnectDB()
	if err != nil {
		lg.Error("Error connecting to database:", err)
		return
	}
	defer db.Close()
	db.Exec("USE PFlib;")
	lg.Info("Executing SQL statement...")
	var klconfig *models.KLConfig
	var openDatas []*models.OpenData
	klconfig, err = models.KLConfigInfo(db)
	if err != nil {
		lg.Error("Error get klconfig :", err)
		return
	}
	openDatas, err = models.OpenDataSelect(db)
	if err != nil {
		lg.Error("Error get openDatas :", err)
		return
	}
	nowt := time.Now().Format("2006-01-02")
	for _, openData := range openDatas {

		outdated, err := handle.GetInOut(klconfig.AppID, klconfig.AccessToken, openData.Openid, openData.PassagewayId, nowt)
		if err != nil {
			lg.Error("getInOut Error:", err)
			lg.Debug("重新获取token")
			InitFun()
			return
		}

		for _, v1 := range outdated.Content {
			lg.Info("时间", v1.Time, "inNum 1 :", v1.In, "outNum 1 :", v1.Out)
			if v1.In != 0 || v1.Out != 0 {
				lg.Info("inNum 3 :", v1.In, "outNum 3 :", v1.Out)

				inNum := v1.In * coefficient.In
				outNum := v1.Out * coefficient.Out
				fmt.Println("inNum 3 :", inNum, "outNum 3 :", outNum)
				// 保存到MonitorHeart_temp
				parseFormat := "2006-01-02 15:04:05"
				timeT, err := time.Parse(parseFormat, v1.Time)
				lg.Info("v1.Time 时间 :", v1.Time)
				if err != nil {
					lg.Error("Error parsing v1.Time:", err)
					return
				}
				// 根据时间获取当前的数据
				currentData, err := models.GetMonitorHeartTemp(db, timeT)
				if err != nil {
					lg.Error("Error getting MonitorHeartTemp:", err)
					return
				}
				if currentData == nil {
					err = models.MonitorHeartTempInsert(db, timeT, inNum, outNum, 0, 0, openData.DevicesOpenid)
					if err != nil {
						lg.Error("Error inserting MonitorHeartTemp:", err)
						return
					}
				}
				if currentData != nil {
					// 1aa
					if currentData.NEnters != inNum || currentData.NExits != outNum {
						err = models.MonitorHeartTempUpdate(db, timeT, inNum, outNum, openData.DevicesOpenid)

						if err != nil {
							lg.Error("Error updateing MonitorHeartTemp:", err)
							return
						}
					}
				}

			}
		}
	}

}
